package com.atjava.webspider.gui.tree;

import java.awt.Component;
import java.awt.Cursor;
import java.util.List;

import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import com.atjava.webspider.gui.SpiderMainGui;
import com.atjava.webspider.gui.table.DefaultTableModel;
import com.atjava.webspider.gui.tree.JFileTree.FileNode;
import com.atjava.webspider.model.Task;
import com.atjava.webspider.services.TableService;

public class JFileTreeListener implements TreeExpansionListener,TreeSelectionListener {
	
	private Component owner;
	
	public JFileTreeListener(Component owner){
		this.owner = owner;
	}

	public void treeExpanded(TreeExpansionEvent event){
        TreePath path = event.getPath();
        if(path == null || path.getLastPathComponent() == null)
            return;
        owner.setCursor(new Cursor(Cursor.WAIT_CURSOR));
        FileNode node = (FileNode)path.getLastPathComponent();
        node.explore();
        JTree tree = (JTree)event.getSource();
        DefaultTreeModel treeModel = (DefaultTreeModel)tree.getModel();
        treeModel.nodeStructureChanged(node);
        owner.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    }
	
	public void treeCollapsed(TreeExpansionEvent event){}
	
	public void refreshTasks(SpiderMainGui mainGui){
		TableService tabService = TableService.getInstance();
		//当前分类路径
		String currentDir = mainGui.getJTree().getSelectFile().getAbsolutePath();
		if(mainGui.getCurrentTaskDir() == null){
			mainGui.setCurrentTaskDir(currentDir);
			return ;
		}
		mainGui.setCurrentTaskDir(currentDir);
		
		//获得当前任务列表
		List<Task> taskList = mainGui.getCurrentTaskList();
		try {
			DefaultTableModel taskModel = mainGui.getTaskModel();
			taskModel.updateAllData(tabService.getTaskTable(taskList));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}
	
	/*public void refreshData(DataGui dataGui){
		TableService tabService = TableService.getInstance();
		DefaultTableModel dataModel = dataGui.getDataModel();
		JFileTree jtree = dataGui.getJTree();
		File dir = jtree.getSelectFile();
		dataModel.updateAllData(tabService.getDataTable(dir.listFiles()));
	}*/

	public void valueChanged(TreeSelectionEvent e) {
		if(owner instanceof SpiderMainGui){
			SpiderMainGui mainGui = (SpiderMainGui)owner;
			refreshTasks(mainGui);
		}
		/*else if(owner instanceof DataGui){
			DataGui dataGui = (DataGui)owner;
			refreshData(dataGui);
		}*/
	}
}
